package com.drama.api.sys.company.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.drama.api.base.Constants;
import com.drama.api.base.Type;
import com.drama.api.sys.company.dao.SysCompanyDao;
import com.drama.api.sys.company.dao.SysCompanyFlowDao;
import com.drama.api.sys.company.domain.po.SysCompanyPO;
import com.drama.api.sys.company.domain.vo.*;
import com.drama.api.sys.company.service.ISysCompanyService;
import com.drama.api.sys.info.domain.vo.*;
import com.drama.api.sys.log.dao.SysLogDao;
import com.drama.api.task.SysLogThread;
import com.drama.exception.BusinessException;
import com.drama.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Transactional
@Slf4j
public class SysCompanyServiceImpl implements ISysCompanyService {

    @Autowired
    private SysCompanyDao sysCompanyDao;
    @Autowired
    private SysLogDao sysLogDao;
    @Autowired
    private SysCompanyFlowDao sysCompanyFlowDao;


    @Override
    public List<SysCompanyVO> getList(SysCompanySearchVO searchVO) {
        return sysCompanyDao.getList(searchVO);
    }

    @Override
    public void update(SysCompanyUpdateVO vo) {
        SysCompanyPO companyPO=sysCompanyDao.selectByPrimaryKey(vo.getId());
        if(companyPO==null){
            throw new BusinessException(Type.NOT_FOUND_ERROR);
        }
        if(StringUtils.isNotBlank(vo.getCompanyName())){
            Example example=new Example(SysCompanyPO.class);
            example.and().andEqualTo("companyName",vo.getCompanyName());
            SysCompanyPO companyOldPO=sysCompanyDao.selectOneByExample(example);
            if(companyOldPO!=null&&!vo.getId().equals(companyOldPO.getId())){
                throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"公司名称不能重复。");
            }
            if(StringUtils.isNotBlank(vo.getCompanyName())&&vo.getCompanyName().length()>30){
                throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"公司名称不能超出30个字符。");
            }
        }
        if(StringUtils.isNotBlank(vo.getCompanyAccount())) {
            Example accountExample = new Example(SysCompanyPO.class);
            accountExample.and().andEqualTo("companyAccount", vo.getCompanyAccount());
            SysCompanyPO accountPO = sysCompanyDao.selectOneByExample(accountExample);
            if (accountPO != null && !vo.getId().equals(accountPO.getId())) {
                throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(), "公司账号不能重复。");
            }
            if(StringUtils.isNotBlank(vo.getCompanyAccount())&&vo.getCompanyAccount().length()>10){
                throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"公司用户名不能超出10个字符。");
            }
        }
        if(StringUtils.isNotBlank(vo.getCompanyReferred())) {
            if(StringUtils.isNotBlank(vo.getCompanyReferred())&&vo.getCompanyReferred().length()>10){
                throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"公司昵称不能超出10个字符。");
            }
        }
        BeanUtils.copyProperties(vo, companyPO);
        companyPO.preUpdate();
        int i = sysCompanyDao.updateByPrimaryKeySelective(companyPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[1],"更新商户信息，商户ID:"+companyPO.getId(), (String) StpUtil.getLoginId()).start();
    }


//    /**
//     * 密码由数字和下划线组成，且大于等于8个字符。
//     */
//    public static boolean isCharacterAndNumber(String password) {
//        String pattern = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,}$";
//        return Pattern.matches(pattern, password);
//    }
    @Override
    public void add(SysCompanyAddVO vo) {
//        if( isCharacterAndNumber(vo.getCompanyPassword())){
//            throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"密码由数字和下划线组成，且大于等于8个字符。");
//        }
        Example example=new Example(SysCompanyPO.class);
        example.and().andEqualTo("companyName",vo.getCompanyName());
        if(sysCompanyDao.selectCountByExample(example)>0){
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"公司名称不能重复。");
        }
        Example accountExample=new Example(SysCompanyPO.class);
        accountExample.and().andEqualTo("companyAccount",vo.getCompanyAccount());
        if(sysCompanyDao.selectCountByExample(accountExample)>0){
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"公司账号不能重复。");
        }
        if(vo.getCompanyName().length()>30){
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"公司名称不能超出30个字符。");
        }
        if(vo.getCompanyAccount().length()>10){
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"公司用户名不能超出10个字符。");
        }
        if(vo.getCompanyReferred().length()>10){
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"公司昵称不能超出10个字符。");
        }
        String imgSuffixName = "";
        if (vo.getCompanyImg().contains(".")) {
            imgSuffixName = vo.getCompanyImg().substring(vo.getCompanyImg().lastIndexOf("."));// 获取文件的后缀名
        }
        boolean ib = !imgSuffixName.equals(".jpg") && !imgSuffixName.equals(".png") && !imgSuffixName.equals(".jpeg");
        if(StringUtils.isBlank(imgSuffixName)|| ib){
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"头像图片格式不对。");
        }
        String covenantSuffixName = "";
        if (vo.getCovenantUrl().contains(".")) {
            covenantSuffixName = vo.getCovenantUrl().substring(vo.getCovenantUrl().lastIndexOf("."));// 获取文件的后缀名
        }
        boolean cb = !covenantSuffixName.equals(".jpg") && !covenantSuffixName.equals(".png") && !covenantSuffixName.equals(".pdf");
        if(StringUtils.isBlank(covenantSuffixName)||cb){
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL.getCode(),"合同文件格式不对。");
        }


        SysCompanyPO companyPO=new SysCompanyPO();
        BeanUtils.copyProperties(vo, companyPO);
        companyPO.preInsert();
        companyPO.setIsArraign(1);
        companyPO.setIsLogin(1);
        companyPO.setIsUpload(1);
        companyPO.setIsWithdraw(1);
        companyPO.setCompanyMoney(BigDecimal.ZERO);
        companyPO.setMaxStorage("524288000");//默认存储空间524288000 500G
        companyPO.setFlowNum(BigDecimal.ZERO.toString());
        companyPO.setStorageNum(BigDecimal.ZERO.toString());
        companyPO.preInsert();
        int i = sysCompanyDao.insertSelective(companyPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[1],"添加入驻商户，商户ID:"+companyPO.getId(), (String) StpUtil.getLoginId()).start();
    }

    @Override
    public void resetPassword(SysCompanyResetPasswordVO vo) {
        SysCompanyPO companyPO=sysCompanyDao.selectByPrimaryKey(vo.getId());
        if(companyPO==null){
            throw new BusinessException(Type.NOT_FOUND_ERROR);
        }
        if(!vo.getCompanyPassword().equals(vo.getConfirmPassword())){
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL);
        }
        companyPO.setCompanyPassword(vo.getCompanyPassword());
        companyPO.preUpdate();
        int i = sysCompanyDao.updateByPrimaryKeySelective(companyPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[1],"重置商户密码，商户ID:"+companyPO.getId(), (String) StpUtil.getLoginId()).start();
    }

    @Override
    public void isLogin(SysCompanyAuthorityVO vo) {
        SysCompanyPO companyPO=sysCompanyDao.selectByPrimaryKey(vo.getId());
        if(companyPO==null){
            throw new BusinessException(Type.NOT_FOUND_ERROR);
        }
        companyPO.setIsLogin(vo.getAuthority());
        companyPO.preUpdate();
        int i = sysCompanyDao.updateByPrimaryKeySelective(companyPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[1],"设置商户登录权限，商户ID:"+companyPO.getId(), (String) StpUtil.getLoginId()).start();
    }

    @Override
    public void isUpload(SysCompanyAuthorityVO vo) {
        SysCompanyPO companyPO=sysCompanyDao.selectByPrimaryKey(vo.getId());
        if(companyPO==null){
            throw new BusinessException(Type.NOT_FOUND_ERROR);
        }
        companyPO.setIsUpload(vo.getAuthority());
        companyPO.preUpdate();
        int i = sysCompanyDao.updateByPrimaryKeySelective(companyPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[1],"设置商户上传视频权限，商户ID:"+companyPO.getId(), (String) StpUtil.getLoginId()).start();
    }

    @Override
    public void isArraign(SysCompanyAuthorityVO vo) {
        SysCompanyPO companyPO=sysCompanyDao.selectByPrimaryKey(vo.getId());
        if(companyPO==null){
            throw new BusinessException(Type.NOT_FOUND_ERROR);
        }
        companyPO.setIsArraign(vo.getAuthority());
        companyPO.preUpdate();
        int i = sysCompanyDao.updateByPrimaryKeySelective(companyPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[1],"设置商户剧目提审权限，商户ID:"+companyPO.getId(), (String) StpUtil.getLoginId()).start();
    }

    @Override
    public void isWithdraw(SysCompanyAuthorityVO vo) {
        SysCompanyPO companyPO=sysCompanyDao.selectByPrimaryKey(vo.getId());
        if(companyPO==null){
            throw new BusinessException(Type.NOT_FOUND_ERROR);
        }
        companyPO.setIsWithdraw(vo.getAuthority());
        companyPO.preUpdate();
        int i = sysCompanyDao.updateByPrimaryKeySelective(companyPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[1],"设置商户提现权限，商户ID:"+companyPO.getId(), (String) StpUtil.getLoginId()).start();
    }

    @Override
    public CompanyStorageCountVO getNumCount() {
        CompanyStorageCountVO companyStorageCountVO=sysCompanyDao.getNumCount();
        if(companyStorageCountVO==null){
            companyStorageCountVO=new CompanyStorageCountVO();
            companyStorageCountVO.setResidueFlowNum(BigDecimal.ZERO.toString());
            companyStorageCountVO.setResidueStorageNum(ToolUtil.formatFileSize(BigDecimal.ZERO.toString()));
            companyStorageCountVO.setUseStorageNum(ToolUtil.formatFileSize(BigDecimal.ZERO.toString()));
            companyStorageCountVO.setUseFlowNum(sysCompanyFlowDao.getCountByMoth());
            companyStorageCountVO.setUseFlowNum(ToolUtil.formatFileSize(BigDecimal.ZERO.toString()));
            return companyStorageCountVO;
        }
        String s="";
        if(new BigDecimal(companyStorageCountVO.getResidueFlowNum()).compareTo(BigDecimal.ZERO)==-1){
            s="-";
        }

        companyStorageCountVO.setResidueFlowNum(s+ToolUtil.formatFileSize(new BigDecimal(companyStorageCountVO.getResidueFlowNum()).abs().toString()));
//        companyStorageCountVO.setResidueFlowNum(ToolUtil.formatFileSize(companyStorageCountVO.getResidueFlowNum()));
        companyStorageCountVO.setResidueStorageNum(ToolUtil.formatFileSize(companyStorageCountVO.getResidueStorageNum()));
//        companyStorageCountVO.setResidueStorageNum("11TB");
        companyStorageCountVO.setUseStorageNum(ToolUtil.formatFileSize(companyStorageCountVO.getUseStorageNum()));
        companyStorageCountVO.setUseFlowNum(sysCompanyFlowDao.getCountByMoth());
        companyStorageCountVO.setUseFlowNum(ToolUtil.formatFileSize(companyStorageCountVO.getUseFlowNum()));
        return companyStorageCountVO;
    }

    @Override
    public List<CompanyStorageVO> getStorageList(CompanyStorageSearchVO searchVO) {
        List<CompanyStorageVO> list=sysCompanyDao.getStorageList(searchVO);
        for (CompanyStorageVO companyStorageVO:list){
            companyStorageVO.setStorageNum(ToolUtil.formatFileSize(companyStorageVO.getStorageNum()));
        }
        return list;
    }


    @Override
    public List<CompanyFlowVO> getFlowList(CompanyFlowSearchVO searchVO) {
        Integer betweenDay = Math.toIntExact(DateUtil.between(DateUtil.parse(searchVO.getStartDate()), DateUtil.parseDate(searchVO.getEndDate()), DateUnit.DAY));
        List<CompanyFlowVO>  list=sysCompanyFlowDao.getFlowList(searchVO);
        HashMap<String,String> maps=new HashMap<>();
        if(list!=null&&list.size()>0){
            maps=(HashMap<String, String>) list.stream().collect(Collectors.toMap(CompanyFlowVO::getDateTime,CompanyFlowVO::getFlowNum));
        }
        List<CompanyFlowVO> result=new ArrayList<>();
        for (int i = 0; i <= betweenDay; i++) {
            CompanyFlowVO companyFlowVO=new CompanyFlowVO();
            companyFlowVO.setDateTime(DateUtil.formatDate(DateUtil.offset(DateUtil.parseDate(searchVO.getStartDate()), DateField.DAY_OF_MONTH, i)));
            companyFlowVO.setFlowNum("0");
            if(maps.containsKey(companyFlowVO.getDateTime())){
                companyFlowVO.setFlowNum(ToolUtil.formatFileSizeGB(maps.get(companyFlowVO.getDateTime())));
//                companyFlowVO.setFlowNum(maps.get(companyFlowVO.getDateTime()));
            }
            result.add(companyFlowVO);
        }
        return result;
    }

    @Override
    public Integer getCount() {
        SysCompanyPO companyPO=new SysCompanyPO();
        return sysCompanyDao.selectCount(companyPO);
    }
}